/*
@auther fenglei
*/
package xxconfig

import (
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
	"path/filepath"
	"strings"
)

var configMap map[string]interface{}

// 初始化配置
func NewConfig(configDir string) error {
	if configDir == "" {
		configDir = filepath.Join(".", "config", "config.toml")
	}
	v := viper.New()
	v.SetConfigFile(configDir)
	//v.AddConfigPath(filepath.Join(gfile.SelfDir(), "config"))
	//v.SetConfigType("toml")
	err := v.ReadInConfig()
	if err != nil {
		return err
	}
	v.WatchConfig()
	v.OnConfigChange(func(e fsnotify.Event) {
		if err = v.Unmarshal(&configMap); err != nil {
			return
		}
	})
	if err = v.Unmarshal(&configMap); err != nil {
		return err
	}
	return nil
}

// 获取配置
func GetConfig(key string) interface{} {
	newKey := strings.ToLower(key)
	return configMap[newKey]
}
